﻿using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using ShanNiang.AutoUpdate.Service.Interfaces;
using ShanNiang.Hosting;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Reflection.Metadata;
using System.Runtime.Versioning;
using System.Text;
using System.Threading.Tasks;

namespace ShanNiang.AutoUpdate.Service.Implementations
{
    /// <summary>
    /// 
    /// </summary>
    [SupportedOSPlatform("windows")]
    public class UpdateService : LocalService, IUpdateService
    {
        private readonly AutoUpdateConfig _autoUpdateConfig;
        public readonly string VersionFilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), CheckVersionService.UserApplicationPath);
        public UpdateService(IOptions<AutoUpdateConfig> autoUpdateConfigOption, ILogger<UpdateService> logger) : base(logger)
        {
            _autoUpdateConfig = autoUpdateConfigOption.Value;
        }

        public void DoUpdate(string packagePath)
        {
            Process process = new Process();
            ProcessStartInfo processStartInfo = new ProcessStartInfo(packagePath);
            processStartInfo.UseShellExecute = true; // 允许使用SHELL外壳打开文档
            process.StartInfo = processStartInfo;
            process.Start();


            //Process.Start(packagePath);
        }

        public async Task<string> DownloadPackageAsync(string packageUrl, Version version)
        {
            if (!Directory.Exists(VersionFilePath))
            {
                Directory.CreateDirectory(VersionFilePath);
            }
            var client = new HttpClient();
            string packageName = Path.Combine(VersionFilePath,  $"{_autoUpdateConfig.PackagePrefix}.{version}.msi");
            var resp = await client.GetAsync(packageUrl);
            if (!resp.IsSuccessStatusCode)
                throw new HttpRequestException("下载更新失败", null, resp.StatusCode);

            using Stream stream = resp.Content.ReadAsStream();
            using FileStream fs = new FileStream(packageName, FileMode.OpenOrCreate, FileAccess.Write);
            stream.CopyTo(fs);
            return packageName;
        }
    }
}
